package com.ruoyi.quartz.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.basedata.domain.RedisKeyName;
import com.ruoyi.basedata.domain.TerminalsXb;
import com.ruoyi.basedata.domain.vo.TerminalsXbProtocol;
import com.ruoyi.basedata.mapper.TerminalsXbMapper;
import com.ruoyi.basedata.service.ITerminalsXbService;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.quartz.service.ISynDeviceIdService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SynDeviceIdServiceImpl implements ISynDeviceIdService {

    private static String factoryCode = "_1002";

    @Autowired
    private TerminalsXbMapper terminalsXbMapper;

    @Autowired
    private ITerminalsXbService terminalsXbService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void job_synchronizationDeviceId() {
        List<TerminalsXb> terminalsXbs = terminalsXbMapper.selectList(new LambdaQueryWrapper<TerminalsXb>()).stream()
                        .filter(terminalsXb -> terminalsXb.getImei() != null)
                        .filter(terminalsXb -> terminalsXb.getDeviceId() == null || terminalsXb.getDeviceId().equals("")).collect(Collectors.toList());
        terminalsXbs.forEach(terminalsXb -> {
            try {
                JSONObject jsonObject = terminalsXbService.queryDeviceList("3aT7YTL4RS5", "kzjEB8xAsj", "f18f125c86614a8084f46fbcb3ee73e6", terminalsXb.getImei());
                JSONObject resultJsonObject = JSONObject.parseObject(jsonObject.getString("result"));
                JSONArray list = resultJsonObject.getJSONArray("list");
                if (list != null && list.size() > 0){
                    JSONObject device = JSONObject.parseObject(list.get(0).toString());
                    String deviceId = device.getString("deviceId");
                    terminalsXb.setDeviceId(deviceId);
                    terminalsXbMapper.updateTerminalsXb(terminalsXb);
                    //更新redis
                    TerminalsXbProtocol terminalsXbProtocol = new TerminalsXbProtocol();
                    terminalsXbProtocol.setImei(terminalsXb.getImei());
                    List<TerminalsXbProtocol> terminalsXbProtocols = terminalsXbService.selectTerminalsXbProtocolList(terminalsXbProtocol);
                    if (terminalsXbProtocols.size() != 0){
                        redisCache.setCacheMapValue(RedisKeyName.terminalInfo + terminalsXbProtocols.get(0).getSupplierId(), terminalsXbProtocols.get(0).getCommunicateAddress(), terminalsXbProtocols.get(0));
                    }
                }
            }catch (Exception e){
                log.info(e.getMessage());
            }

        });
    }
}
